using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.IO;
using Docuverse.Identicon;

namespace Identicon.WebDemo
{
  /// <summary>
  /// Demo Identicon Handler with hard-coded salt and no caching
  /// **do not use this demo handler on a production website**; use IdenticonHandler.ashx.
  /// </summary>
  /// <author>Jeff Atwood http://www.codinghorror.com/, Jon Galloway http://weblogs.asp.net/jgalloway/</author>
  public class IdenticonHandlerDemo : IHttpHandler
  {
    private IdenticonRenderer _renderer = new IdenticonRenderer();

    // sanity check:
    // IP 127.0.0.1 with salt = "chittychittybangbang" should produce..
    //   * identicon code of -1167887624
    //   * a brown "X" shape in the rendered image (see identicon-samples.png)

    public void ProcessRequest(HttpContext context)
    {
      HttpRequest request = context.Request;
      HttpResponse response = context.Response;
      int code;
      int size;

      IdenticonUtil.Salt = "chittychittybangbang";

      if (!string.IsNullOrEmpty(request["ip"]))
      {
        code = IdenticonUtil.Code(request["ip"]);
      }
      else
      {
        code = IdenticonUtil.Code(request.UserHostAddress);
      }
      Int32.TryParse(request["size"], out size);

      Bitmap b = _renderer.Render(code, size);
      RenderPNG(response, b);
      HttpContext.Current.ApplicationInstance.CompleteRequest();
    }

    /// <summary>
    /// http://west-wind.com/WebLog/posts/8230.aspx
    /// </summary>
    private void RenderPNG(HttpResponse response, Bitmap b)
    {
      response.ContentType = "image/png";
      MemoryStream ms = new MemoryStream();
      b.Save(ms, ImageFormat.Png);
      ms.WriteTo(response.OutputStream);
      b.Dispose();
    }

    public bool IsReusable
    {
      get { return true; }
    }
  }
}
